<script setup lang="ts">
    import { onMounted, ref } from "vue";
    import YunWordleLetter from "./YunWordleLetter.vue";
    import eventBus from "@/modules/EventBus";

    const inputElement = ref<HTMLInputElement>();
    const draft = ref("     ");

    const handleSubmit = (e: InputEvent) => {
        e.preventDefault();
        eventBus.emit("INPUT:SUBMIT", e.target);
    };

    onMounted(() => {
        const inEl = inputElement.value;
        if (!inEl) throw new Error("Form element is not found!");
        document.addEventListener("keydown", () => {
            inEl?.focus();
        });
        inEl?.addEventListener("input", () => {
            inEl.value = inEl.value.replace(/[^a-zA-Z]/g, "");
            draft.value = inEl.value.padEnd(5, " ");
        });
    });
</script>

<template>
    <div class="YunDraft">
        <h2>Draft</h2>
        <!-- @vue-ignore -->
        <form @submit="handleSubmit">
            <input
                ref="inputElement"
                autofocus
                type="text"
                id="draft-input"
                maxlength="5" />
        </form>
        <div id="line">
            <YunWordleLetter
                v-for="order in [0, 1, 2, 3, 4]"
                :key="order"
                :letter="draft[order] ?? ``"
                state="empty">
            </YunWordleLetter>
        </div>
    </div>
</template>

<style lang="scss" scoped>
    div.YunDraft {
        form {
            height: 0;
            opacity: 0;
        }
        div#line {
            display: flex;
        }
    }
</style>
